package com.example.demo.controller;

import com.example.demo.annotation.Limit;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class LimitController {

    /**
     * 限流策略 ： 1秒钟2个请求
     */
    private final RateLimiter limiter = RateLimiter.create(1);

    private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Limit(key = "limit1", permitsPerSecond = 2, timeout = 500, timeunit = TimeUnit.MILLISECONDS,msg = "系统繁忙，请稍后再试！")
    @GetMapping("limit1")
    public Object testLimiter() {
//        //500毫秒内，没拿到令牌，就直接进入服务降级
//        boolean tryAcquire = limiter.tryAcquire(5, TimeUnit.MINUTES);
//
//        if (!tryAcquire) {
//            log.warn("进入服务降级，时间{}", LocalDateTime.now().format(dtf));
//            return "当前排队人数较多，请稍后再试！";
//        }
//
//        log.info("获取令牌成功，时间{}", LocalDateTime.now().format(dtf));
        return "请求成功";
    }

}
